package com.youdoneed.friends.common.util;

import com.youdoneed.base.application.AppException;
import com.youdoneed.base.common.OkHttpUtils;
import com.youdoneed.friends.common.config.HuanXinConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HuanXinUtil {
    private final static Logger logger = LoggerFactory.getLogger(HuanXinUtil.class);

    public static final String AccessTokenKey = "EasemobAccessToken";

    public static class AccessTokenResult {
        public String access_token;
        public int expires_in;
        public String application;
    }

    public static String getAccessToken() {
        String apiUrl = HuanXinConfig.url + "token";
        String accessToken = EHCacheUtil.get(AccessTokenKey);
        if (accessToken == null) {
            try {
                AccessTokenResult result = OkHttpUtils.bodyPost(apiUrl)
                        .param("grant_type", HuanXinConfig.grant_type)
                        .param("client_id", HuanXinConfig.client_id)
                        .param("client_secret", HuanXinConfig.client_secret)
                        .callJsonObject(AccessTokenResult.class);
                EHCacheUtil.put(AccessTokenKey, result.access_token,
                        result.expires_in - 60);
                accessToken = result.access_token;
            } catch (Exception e) {
                logger.error("获取环信AccessToken失败：" + e);
                throw new AppException("获取环信AccessToken失败。");
            }
        }
        return accessToken;
    }

}
